package com.study.easyexcel.api.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.study.easyexcel.common.exception.ExcelImportException;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 属性映射的异常处理
 *
 * @author yuhuan
 * @date 2023/5/12
 */
public abstract class HealthMonitoring<T> extends AnalysisEventListener<T> {

    /**
     * 导入的表头
     */
    protected List<String> headerList;

    /**
     * 任何子类在重写本方法时都应该主动初始化表头列表
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headerList = new ArrayList<>(headMap.values());
    }

    /**
     * 异常处理，字段映射出现异常的情况下调用；抛出异常则停止读取。如果这里不抛出异常则继续读取下一行
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if (exception instanceof ExcelDataConvertException) {
            Integer columnIndex = ((ExcelDataConvertException) exception).getColumnIndex();
            Integer rowIndex = ((ExcelDataConvertException) exception).getRowIndex();
            Cell cell = context.readRowHolder().getCellMap().get(columnIndex);
            String columnData = ((ReadCellData<?>) cell).getStringValue();
            String headerName = "";
            if (!ObjectUtils.isEmpty(headerList)) {
                headerName = headerList.get(columnIndex);
            }
            throw new ExcelImportException("第" + (rowIndex + 1) + "行数据" + headerName + "，[" + columnData + "]的格式错误!");
        }
        super.onException(exception, context);
    }
}
